import ROSLIB from "roslib";

/**
 * 解析传入的数据字符
 * 数据格式: "mapname","mapname","mapname"
 * @param {string} str 传入的数据字符
 */
function parse(str) {
  var list = str.split(",");
  var L = [];
  for (var i = 0, l = list.length; i < l; i++) {
    var prefix = list[i].split(".");
    console.log("prefix:" + prefix[0]);
    if (!L.includes(prefix[0])) {
      L.push(prefix[0]);
    }
  }
  console.log("L:" + L);
  return L;
}

/**
 * 获取地图列表
 * @param {ROSLIB.Ros} roslink 
 * @param {object} self 
 * @param {function} callback 
 */
function getMapList(roslink = null, self, callback) {
  // console.log(roslink.isConnected);
  if (roslink.isConnected) {
    var listClient = new ROSLIB.Service({
      ros: roslink,
      name: "/add_two_ints",
      serviceType: "rospy_tutorials/AddTwoInts",
    });

    var request = new ROSLIB.ServiceRequest({
      name: "load",
      a: 0,
      p: "s",
    });

    listClient.callService(
      request,
      function (result) {
        // callback success  
        try {
          var array = parse(result.feedback);
        } catch {
          console.log("parse failed");
        }
        callback(self, array);
      },
      function () {
        // callback failed
        console.log("Service Request failed");
        var failedArray = ["Service Request failed", "也许是连接中断"];
        callback(self, failedArray);
      }
    );
    return true;
  } else {
    return false;
  }
}

/**
 * 读取地图
 * @param {string} map 地图文件名(不包含后缀)
 */
function loadMap(map) {
  console.log("load map:" + map);
}

export { getMapList, loadMap };
